<template>
	<view class="">
		<view class="item-box" v-for="item in list">
			<view class="u-flex">
				<image src="../../static/key.png" style="width: 45rpx;height: 45rpx;"></image>
				<view class="u-flex-1 m-l-10 font-16">{{item.name}}</view>
				<u-icon name="more-dot-fill" @click="goFunctions(item.deviceId)" size="28"></u-icon>
			</view>
			<view class="u-flex u-row-around m-t-20">
				<image @click="handleUnclock(item.deviceId)" src="../../static/open-lock.png" style="width: 70rpx;height: 70rpx;"></image>
				<image @click="handleLock(item.deviceId)" src="../../static/close-lock.png" style="width: 70rpx;height: 70rpx;"></image>
				<image @click="handleShare(item.deviceId)" src="../../static/share.png" style="width: 70rpx;height: 70rpx;"></image>
			</view>
		</view>
		<view style="margin-top: 25vh;" v-if="list.length == 0">
			<u-empty></u-empty>
		</view>
		<view class="folat-box">
			<u-icon @click="goSearchBlueTooth" name="plus-circle-fill" size="60" color="#007AFF"></u-icon>
		</view>
	</view>
</template>

<script>
	import {
		getUser,
		getDevice,
		getLastConnectedDevice
	} from "../../utils/storage";
	import {
		getUuid,
		writeBLECharacteristicValue,
		writeBLECharacteristicValueByDevice
	} from "../../utils/common";
	import {
		guid
	} from "../../utils/util";
	const db = uniCloud.database();
	export default {
		data() {
			return {
				list: [],
				bluetoothShow: false,
				openid: "",
				connected: false,
				deviceId: "",
				timer:"",
			}
		},
		onLoad() {
			
		},
		onPullDownRefresh() {
			let app = getApp();
			app.globalData.deviceId = '';
			// this.deviceId = "";
			// this.init();
			uni.reLaunch({
				url:'/pages/index/index'
			})
		},
		onShow() {
			this.init();
		},
		onUnload() {
			this.deviceId = "";
		},
		methods: {
			init() {
				const userInfo = getUser();
				if(userInfo && userInfo.openid){
					this.openid = userInfo?.openid;
				}else{
					uni.navigateTo({
						url:"/pages/login/login"
					})
				}
				this.getListData();
				this.openBluetoothAdapter();
			},
			async getListData() {
				const deviceList = getDevice();
				
				console.log('deviceList: ',deviceList);
				const listData = deviceList.map((item) => ({
					...item,
					id: guid()
				}));
				console.log(listData);
				
				const res = await db.collection("devices").where({
					userId:this.openid
				}).get();
				if(res.result.errCode == 0){
					let cloudDevices = res.result.data;
					for (let i = 0; i < cloudDevices.length; i++) {
						let isHave = listData.find(obj => obj.deviceId === cloudDevices[i].deviceId);
						if(!isHave){
							listData.push({
								...cloudDevices[i],
								id:guid()
							})
						}
					}
					for (let i = 0; i < listData.length; i++) {
						let isHave = cloudDevices.find(obj => obj.deviceId === listData[i].deviceId);
						if(!isHave){
							await db.collection("devices").add({
								name:listData[i].name,
								deviceId:listData[i].deviceId,
								userId:this.openid
							});
						}
					}
				}
				this.list = listData;
			},
			async handleUnclock(deviceid) {
				const deviceDta = this.list.find((item) => item.deviceId === deviceid);
				console.log('deviceDta: ',deviceDta);
				await this._createBLEConnection(deviceDta, true);
				const serviceId = getUuid("5508");
				writeBLECharacteristicValueByDevice(deviceid, serviceId, getUuid("0080"), "", "开锁");
			},
			async handleLock(deviceid) {
				const deviceDta = this.list.find((item) => item.deviceId === deviceid);
				await this._createBLEConnection(deviceDta, true);
				const serviceId = getUuid("5508");
				writeBLECharacteristicValueByDevice(deviceid, serviceId, getUuid("0081"), "", "关锁");
			},
			async handleShare(deviceid) {
				const deviceDta = this.list.find((item) => item.deviceId === deviceid);
				await this._createBLEConnection(deviceDta, true);
				const serviceId = getUuid("5508");
				writeBLECharacteristicValueByDevice(deviceid, serviceId, getUuid("0082"), "", "停止");
			},
			//监听蓝牙连接状态
			listenConnectState(){
				// 监听蓝牙连接状态变化事件
				uni.onBLEConnectionStateChange((res) => {
				  console.log('蓝牙连接状态变化:', res);
				  // 当连接断开时，尝试重新连接
				  if (!res.connected) {
					  console.log('重新连接。。。。。');
				    // 调用重新连接的函数
					// this.timer = setInterval(() => {
					// 	this.init();
					// },2000);
				  }else{
					  if(this.timer){
						  clearInterval(this.timer);
					  }
				  }
				});
			},
			openBluetoothAdapter() {
				uni.openBluetoothAdapter({
					success: (res) => {
						console.log("openBluetoothAdapter success", res);
						uni.getConnectedBluetoothDevices({
							success(res) {
								console.log("ConnectedBluetoothDevices ==>",res);
							},
							fail: (res) => {
								console.log(res);
							},
						});
						// this.createBLEConnectionLastDevice();
					},
					fail: (res) => {
						console.log("openBluetoothAdapter fail", res);
						if (res.errCode === 10001) {
							uni.showModal({
								title: "连接不成功",
								content: `请确定手机蓝牙已打开`,
								showCancel: false,
								confirmText: "好",
								success() {},
							});
							uni.onBluetoothAdapterStateChange((res) => {
								console.log("onBluetoothAdapterStateChange", res);
								if (res.available) {
									// 取消监听，否则stopBluetoothDevicesDiscovery后仍会继续触发onBluetoothAdapterStateChange，
									// 导致再次调用startBluetoothDevicesDiscovery
									uni.onBluetoothAdapterStateChange(() => {});
								}
							});
						}
					},
				});
			},
			goSearchBlueTooth() {
				uni.navigateTo({
					url: "/pages/search-bluetooth/search-bluetooth"
				})
			},
			async goFunctions(deviceid) {
				const deviceDta = this.list.find((item) => item.deviceId === deviceid);
				await this._createBLEConnection(deviceDta, true);
				uni.navigateTo({
					url: "/pages/function-list/function-list"
				})
			},
			checkUser() {
				const userInfo = getUser();
				const {
					openid
				} = userInfo;
				const serviceId = getUuid("5508");
				writeBLECharacteristicValue(serviceId, getUuid("0083"), openid);
			},
			_createBLEConnection(data, isAction) {
				let self = this;
				return new Promise((resolve, reject) => {
					const {
						deviceId,
						name
					} = data;
					let app = getApp();
					console.log(app.globalData.deviceId, deviceId);
					if (app.globalData.deviceId === deviceId) {
						uni.getConnectedBluetoothDevices({
							success(res) {
								console.log('getConnectedBluetoothDevices success',res);
								if(res.devices.length == 0){
									console.log("重新连接====");
									app.globalData.deviceId = '';
									self._createBLEConnection(data,false);
								}else{
									resolve();
								}
							},
							fail(res) {
								console.log('getConnectedBluetoothDevices fail',res);
								app.globalData.deviceId = '';
								// self._createBLEConnection(data,false);
							},
						});
						return;
					}
					if (isAction) {
						uni.showLoading({
							title: "连接中...",
						});
					}
					uni.createBLEConnection({
						deviceId,
						success: () => {
							console.log("createBLEConnection success");
							//监听连接状态
							// this.listenConnectState();
							if(isAction){
								uni.hideLoading();
							}
							// uni.showToast({
							//   title: `蓝牙设备“${name}”连接成功`,
							//   icon: "none",
							//   duration: 2000,
							// });

							app.globalData.deviceId = deviceId;
							this.connected = true;
							this.deviceId = deviceId;
							// this.checkUser();
							resolve();
						},
						fail: (res) => {
							if (res.errCode === -1) {
								app.globalData.deviceId = deviceId;
								resolve();
								return;
							}
							app.globalData.deviceId = "";
							this.deviceId = "";
							console.log("createBLEConnection fail", res);
							uni.hideLoading();
							if (isAction) {
								uni.showModal({
									title: "连接不成功",
									content: `请确定“${name}”已打开而且在通信范围内`,
									showCancel: false,
									confirmText: "好",
									success() {
										reject();
									},
								});
							}
						},
					});
					
				});
			},

		}
	}
</script>

<style lang="scss" scoped>
	.item-box {
		padding: 20rpx;
		margin: 30rpx 40rpx 0 40rpx;
		background: linear-gradient(270deg, #FFFFFF 0%, #E1EBFC 100%);
		box-shadow: 0px 4px 8px 0px rgba(0, 0, 0, 0.15);
		border-radius: 15rpx;
	}

	.folat-box {
		position: fixed;
		bottom: 50rpx;
		right: 40rpx;
	}
</style>